
// Copyright (C) 2010-2011 Luca Piccioni
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//   
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;

using Derm.OpenGL;
using Derm.Raster;

namespace Derm.Render
{
	/// <summary>
	/// Texture set management service.
	/// </summary>
	internal class TextureService : RenderKernelService
	{
		#region Constructors
		
		/// <summary>
		/// Constructor a TextureService.
		/// </summary>
		public TextureService() : base(ThisServiceName, ExecutionModel.MultithreadContext)
		{
			
		}

		/// <summary>
		/// This service name.
		/// </summary>
		private static readonly string ThisServiceName = "Derm.Render.TextureService";

		#endregion

		#region Service Tasks

		/// <summary>
		/// Request a texture creation.
		/// </summary>
		/// <param name="tex"></param>
		public void RequestCreation(Texture tex)
		{
			if (tex == null)
				throw new ArgumentNullException("tex");

			lock (mTexCreate) {
				mTexCreate.Enqueue(tex);
			}
		}

		/// <summary>
		/// Request texture mipmaps creation.
		/// </summary>
		/// <param name="tex"></param>
		public void RequestMipmaps(Texture tex)
		{
			lock (mTexGenerateMipmaps) {
				mTexGenerateMipmaps.Enqueue(tex);
			}
		}

		/// <summary>
		/// Texture creation queue.
		/// </summary>
		private Queue<Texture> mTexCreate = new Queue<Texture>();

		/// <summary>
		/// Texture mipmaps creation queue.
		/// </summary>
		private Queue<Texture> mTexGenerateMipmaps = new Queue<Texture>();

		#endregion

		#region RenderKernelService Overrides

		public static TextureService GetService(Guid rObjectNameSpace)
		{
			return ((TextureService)GetService(rObjectNameSpace, ThisServiceName));
		}

		public override void ContextExecute(RenderContext ctx)
		{
			
		}

		protected override void ThreadExecute(RenderContext ctx)
		{
			// Texture creation
			lock (mTexCreate) {
				foreach (Texture tex in mTexCreate)
					tex.Create(ctx);
				mTexCreate.Clear();
			}
			// Texture mipmaps creation
			lock (mTexGenerateMipmaps) {
				foreach (Texture tex in mTexGenerateMipmaps)
					tex.GenerateMipmaps(ctx);
				mTexGenerateMipmaps.Clear();
			}
		}

		#endregion
	}
}
